package com.itcoon.cloud.framework.utils;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.GenericApplicationContext;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Miaoxia Yu
 * @date 2020-09-16
 */
public class SpringUtils implements ApplicationContextAware {

    private static ApplicationContext ctx;

    @Override
    public void setApplicationContext(ApplicationContext ctx) throws BeansException {
        SpringUtils.ctx = ctx;
    }

    public static ApplicationContext getContext(){
        return ctx;
    }

    public static  <T> T getBean(Class<T> beanClass){
        T t = null;
        try {
            t = ctx.getBean(beanClass);
        }catch (Exception e){
            e.printStackTrace();
        }
        return t;
    }

    public static <T> Map<String,T> getBeansMap(Class<T> beanClass){
        Map<String,T> map = new HashMap<>();
        try {
            map = ctx.getBeansOfType(beanClass);
        }catch (Exception e){
            e.printStackTrace();
        }
        return map;
    }

    public static <T> T getBean(String beanName, Class<T> beanClass) {
        T t = null;
        try {
            t = ctx.getBean(beanName, beanClass);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return t;
    }

    public static void registerSingleton(Object bean){
        String className = bean.getClass().getSimpleName();
        registerSingleton(className.substring(0, 1).toLowerCase() + className.substring(1), bean);
    }

    public static void registerSingleton(String beanName, Object bean){
        GenericApplicationContext genericApplicationContext = (GenericApplicationContext) ctx;
        DefaultListableBeanFactory defaultListableBeanFactory = genericApplicationContext.getDefaultListableBeanFactory();
        defaultListableBeanFactory.registerSingleton(beanName, bean);
    }

    public static void registerAndAutowireBean(String beanName, Class<?> beanClass){
        DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory)ctx.getAutowireCapableBeanFactory();
        BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(beanClass);
        if(!beanFactory.containsBeanDefinition(beanName)){
            beanFactory.registerBeanDefinition(beanName, beanDefinitionBuilder.getBeanDefinition());
            Object bean = ctx.getBean(beanName);
            ctx.getAutowireCapableBeanFactory().autowireBean(bean);
        }
    }

    public static String getApplicationName(){
        return ctx.getEnvironment().getProperty("spring.application.name");
    }
}
